/**
 * Created by lh on 2017/10/25.
 */
import {Injectable} from "@angular/core";

@Injectable()
export class WebSocket {
  socket: any;
  stompClient: any;

  // 开启socket连接
  connect(activityId: number) {
    let that = this;
    this.socket = new SockJS('http://localhost:8084/socket');
    this.stompClient = Stomp.over(this.socket);
    this.stompClient.connect({}, function () {
      that.stompClient.subscribe('/topic/track/activity/' + activityId, function (data) {
        console.log("realTrack:" + data.body);
      });
      that.send(1);
    });
  }

  // 断开socket连接
  disconnect() {
    if (this.stompClient != null) {
      this.stompClient.disconnect();
    }
    console.log("Disconnected");
  }

// 向‘/app’服务端发送消息
  send(activityId: number) {
    let realTrack = {
      activityId: activityId,
      userId: 1,
      latitude: 104.136288,
      longtitude: 30.584049
    };
    this.stompClient.send("/app/data/handle", {}, JSON.stringify(realTrack));
  }

}
